<template>
  <div
    class="setting-container"
    ref="settingMainRef"
    @scroll="handleScroll"
  >
    <div class="setting-tabs-wrap">
      <el-tabs
        tab-position="left"
        class="setting-tabs t-tabs"
        @tab-change="handleTabChange"
        v-model="activeName"
        ref="tabElRef"
      >
        <el-tab-pane
          :label="$t('form.setting.examSettingLabel')"
          v-if="formType === 4 && hasFormButtonAuth('exam')"
          name="exam"
        >
          <template #label>
            <el-icon>
              <ele-School />
            </el-icon>
            {{ $t("form.setting.examSettingLabel") }}
          </template>
        </el-tab-pane>
        <el-tab-pane
          :label="$t('form.setting.submitSettingLabel')"
          name="submit"
          v-if="hasFormButtonAuth('submit')"
        >
          <template #label>
            <el-icon size="22">
              <TablerCircleCheck />
            </el-icon>
            {{ $t("form.setting.submitSettingLabel") }}
          </template>
        </el-tab-pane>
        <el-tab-pane
          :label="$t('form.setting.recoverySettingLabel')"
          name="write"
          v-if="hasFormButtonAuth('write')"
        >
          <template #label>
            <el-icon size="22">
              <TablerDeviceMobileCheck />
            </el-icon>
            {{ $t("form.setting.recoverySettingLabel") }}
          </template>
        </el-tab-pane>
        <el-tab-pane
          :label="$t('form.setting.notificationSettingLabel')"
          name="notify"
          v-if="hasFormButtonAuth('notify')"
        >
          <template #label>
            <el-icon size="22">
              <TablerBellPlus />
            </el-icon>
            {{ $t("form.setting.notificationSettingLabel") }}
          </template>
        </el-tab-pane>
        <el-tab-pane
          :label="$t('form.setting.sharingSettingLabel')"
          name="share"
          v-if="hasFormButtonAuth('share')"
        >
          <template #label>
            <el-icon size="22">
              <TablerShare2 />
            </el-icon>
            {{ $t("form.setting.sharingSettingLabel") }}
          </template>
        </el-tab-pane>
        <el-tab-pane
          :label="$t('form.setting.replySettingLabel')"
          name="reply"
          v-if="hasFormButtonAuth('reply')"
        >
          <template #label>
            <el-icon size="22">
              <TablerMessage2Cog />
            </el-icon>
            {{ $t("form.setting.replySettingLabel") }}
          </template>
        </el-tab-pane>
        <el-tab-pane
          :label="$t('form.setting.teamworkSettingLabel')"
          name="teamwork"
          v-if="hasFormButtonAuth('teamwork')"
        >
          <template #label>
            <el-icon size="22">
              <TablerUsersPlus />
            </el-icon>
            {{ $t("form.setting.teamworkSettingLabel") }}
          </template>
        </el-tab-pane>
      </el-tabs>
      <div
        class="content-wrap"
        :style="{ marginLeft: tabWidth + 'px' }"
      >
        <exam-setting
          :ref="(el: any) => (settingRefs['exam'] = el)"
          v-if="formType === 4 && hasFormButtonAuth('exam')"
        />
        <submit-setting
          class="mt20"
          :ref="(el: any) => (settingRefs['submit'] = el)"
          v-if="hasFormButtonAuth('submit')"
          :settingConf="settingConf"
          @update="handleSettingUpdate"
        />
        <write-setting
          class="mt20"
          :ref="(el: any) => (settingRefs['write'] = el)"
          v-if="hasFormButtonAuth('write')"
          :settingConf="settingConf"
          @update="handleSettingUpdate"
        />
        <notify-setting
          class="mt20"
          :ref="(el: any) => (settingRefs['notify'] = el)"
          v-if="hasFormButtonAuth('notify')"
          :settingConf="settingConf"
          @update="handleSettingUpdate"
        />
        <share-setting
          class="mt20"
          :ref="(el: any) => (settingRefs['share'] = el)"
          v-if="hasFormButtonAuth('share')"
          :settingConf="settingConf"
          @update="handleSettingUpdate"
        />
        <reply-setting
          class="mt20"
          :ref="(el: any) => (settingRefs['reply'] = el)"
          v-if="hasFormButtonAuth('reply')"
          :settingConf="settingConf"
          @update="handleSettingUpdate"
        />
        <teamwork-setting
          class="mt20 mb20"
          :ref="(el: any) => (settingRefs['teamwork'] = el)"
          v-if="hasFormButtonAuth('teamwork')"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="ProjectSetting">
import { onBeforeMount, onMounted, ref } from "vue";
import { loadAsyncComponent } from "@/utils/asyncComponent";
import { useFormInfo } from "@/stores/formInfo";
import { storeToRefs } from "pinia";
import { useDebounceFn, useElementSize } from "@vueuse/core";
import { getSettingRequest, saveSettingRequest } from "@/api/project/setting";
import { useRoute } from "vue-router";
import { i18n } from "@/i18n";
import { MessageUtil } from "@/utils/messageUtil";
import TablerCircleCheck from "~icons/tabler/circle-check";
import TablerDeviceMobileCheck from "~icons/tabler/device-mobile-check";
import TablerBellPlus from "~icons/tabler/bell-plus";
import TablerShare2 from "~icons/tabler/share-2";
import TablerMessage2Cog from "~icons/tabler/message-2-cog";
import TablerUsersPlus from "~icons/tabler/users-plus";
const SubmitSetting = loadAsyncComponent(() => import("./submit.vue"));
const WriteSetting = loadAsyncComponent(() => import("./write.vue"));
const NotifySetting = loadAsyncComponent(() => import("./notify.vue"));
const ShareSetting = loadAsyncComponent(() => import("./share.vue"));
const TeamworkSetting = loadAsyncComponent(() => import("./teamwork.vue"));
const ReplySetting = loadAsyncComponent(() => import("./reply.vue"));
const ExamSetting = loadAsyncComponent(() => import("./exam.vue"));
const formInfoStore = useFormInfo();

const { formType } = storeToRefs(formInfoStore);

const activeName = ref(formType.value == 4 ? "exam" : "submit");

const { hasFormButtonAuth } = useFormInfo();

const settingRefs = ref<any>({});

onBeforeMount(() => {
  queryUserProjectSetting();
});

onMounted(() => {
  if (!activeName.value) {
    handleTabChange(activeName.value);
  }
});

const route = useRoute();

const settingConf = ref({
  // *****提交设置 开始
  // 提交后显示类型
  submitShowType: 1,
  // 自定义显示内容
  submitShowCustomPageContent:
    '<p><img style="display: block; margin-left: auto; margin-right: auto;" src="" /></p>\n<p style="text-align: center;"><strong>提交成功</strong></p>',
  submitJump: false,
  submitJumpUrl: "",
  publicResult: false,
  // 可查看已提交内容
  showSubmitContentBtn: false,
  // 可以修改已经提交的内容
  updateSubmitContentBtn: false,
  // *******提交设置结束************
  // *******填写设置开始******
  // 仅在微信填写
  onlyWxWrite: false,
  // 记录微信用户信息
  recordWxUser: false,
  // 恢复提交数据
  saveSubmitStatus: false,
  // 保存未恢复数据
  saveNotSubmitStatus: false,
  // 密码填写状态
  passwordWriteStatus: false,
  // 填写密码
  writePassword: "",
  // 每个微信答题次数限制
  wxWriteCountLimitStatus: false,
  // 次数
  wxWriteCountLimit: 1,
  // 日期范围
  wxWriteCountLimitDateType: 1,
  // 文案
  wxWriteCountLimitText: "",
  // 每个IP答题次数限制
  ipWriteCountLimitStatus: false,
  // 次数
  ipWriteCountLimit: 1,
  // 日期范围
  ipWriteCountLimitDateType: 1,
  // 文案
  ipWriteCountLimitText: "",
  // 限制填写的位置
  ipWriteLocationRangeStatus: false,
  // 具体位置
  ipWriteLocationRange: [],
  // 每个账号答题次数限制
  accountWriteCountLimitStatus: false,
  // 次数
  accountWriteCountLimit: 1,
  // 日期范围
  accountWriteCountLimitDateType: 1,
  // 文案
  accountWriteCountLimitText: "",
  // 每台设备答题次数限制
  deviceWriteCountLimitStatus: false,
  // 次数
  deviceWriteCountLimit: 1,
  // 文案
  deviceWriteCountLimitText: "",
  // 累计答题数量
  totalWriteCountLimitStatus: false,
  // 次数
  totalWriteCountLimit: 1,
  // 日期范围
  totalWriteCountLimitDateType: 1,
  // 文案
  totalWriteCountLimitText: "",
  // 访问时间
  writeInterviewTimeStatus: false,
  // 访问时间是否是一天内的某些小时
  writeInterviewDayTimeStatus: false,
  // 允许访问访问时间范围
  writeInterviewDateTimeRange: [],
  // 允许访问访问日期范围
  writeInterviewDateRange: [],
  // 允许访问访问时间范围
  writeInterviewTimeRange: null,
  // 每周允许周几访问
  writeInterviewTimeWhichDays: [],
  writeInterviewTimeText: "",
  // 必须登录
  mustLogin: false,
  // 是否启用白名单
  enableWhiteList: false,
  // 白名单类型
  whiteListType: 3,
  // 每页一题‘
  onePageOneQuestion: {
    enableOnePageOneQuestion: false,
    enableShortestStay: false,
    shortestStayTime: 1,
    enableLongestStay: false,
    longestStayTime: 60,
    autoNext: false
  },
  anonymousWrite: false,
  // 启用进度条
  enableProgress: false,
  // 再次填写按钮
  enableAgainWrite: false,
  // *****填写设置结束******
  // *** 通知设置**************
  emailNotify: false,
  newWriteNotifyEmail: null,
  wxNotify: false,
  newWriteNotifyWx: null,
  // *****通知设置结束**************
  // 分享设置开始****
  shareWxImg: false,
  shareWxImgUrl: null,
  shareWxTitle: false,
  shareWxTitleContent: null,
  shareWxDesc: false,
  shareWxDescContent: null
  // 分享设置结束****
});

const queryUserProjectSetting = () => {
  getSettingRequest(route.query.key as string).then(res => {
    if (res.data) {
      settingConf.value = Object.assign(settingConf.value, res.data);
      console.log(settingConf.value);
    }
  });
};

const handleSettingUpdate = (setting: any) => {
  setting.formKey = route.query.key as string;
  saveSettingRequest(setting).then(() => {
    MessageUtil.success(i18n.global.t("formI18n.all.success"));
  });
};

const handleTabChange = (name: string) => {
  console.log(name);
  console.log(settingRefs.value[name]);
  settingRefs.value[name].$el.scrollIntoView({ behavior: "smooth", block: "start" });
};

const tabElRef = ref(null);
const { width: tabWidth } = useElementSize(tabElRef);

const handleScroll = useDebounceFn(() => {
  activeName.value = getCurrentScrollDom();
}, 300);

const settingMainRef = ref<HTMLDivElement | null>(null);

const getCurrentScrollDom = () => {
  const current = settingMainRef.value!.scrollTop + 20; // 获取当前滚动条离顶部高度
  let currentTab = "";
  let maxTop = 0;
  for (let key of Object.keys(settingRefs.value)) {
    const top = settingRefs.value[key].$el.offsetTop;
    if (current + 200 > top && top > maxTop) {
      currentTab = key;
      maxTop = top;
    }
  }
  return currentTab;
};
</script>

<style lang="scss" scoped>
.setting-container {
  height: calc(100vh - 46px);
  background-color: var(--el-bg-color-page);
  overflow: auto;
  position: relative;
  z-index: 10;
  width: 100%;

  .setting-tabs-wrap {
    margin: 0 auto;
    width: 980px;
  }

  .setting-tabs {
    border-radius: 8px;
    margin-top: 20px;
    min-height: 500px;
    position: fixed;
    top: 66px;
    z-index: 10;
    --el-color-primary-light-9: var(--el-bg-color-page);
    :deep(.el-tabs__item.is-active) {
      color: var(--el-text-color-primary);
    }
  }
  .content-wrap {
    width: 780px;
    padding-top: 20px;
    padding-bottom: 100px;
  }
}
:deep(.el-tabs__item) {
  justify-content: left !important;
}
</style>
